<!-- pages/merchant/manual-settlement.vue -->
<template>
	<view class="container">
		<!-- 订单查询区域 -->
		<view class="search-card">
			<view class="search-title">订单查询</view>
			<view class="search-options">
				
				<view class="search-input-box">
					<input type="text" class="search-input" v-model="searchKey" placeholder="请输入订单号"
						@confirm="searchOrder" />
					<view class="search-btn" @tap="searchOrder">查询</view>
				</view>
			</view>
		</view>

		<!-- 扫码区域 -->
		<view class="scan-card">
			<view class="scan-title">扫码查询</view>
			<view class="scan-options">
				<view class="scan-option-btn" @tap="scanOrderCode">
					<view class="scan-icon">🔍</view>
					<text>扫订单码</text>
				</view>
				<view class="scan-option-btn" @tap="scanStrollerCode">
					<view class="scan-icon">🔍</view>
					<text>扫车辆码</text>
				</view>
			</view>
		</view>

		<!-- 订单信息区域 -->
		<block v-if="currentOrder">
			<view class="order-card">
				<view class="order-header">
					<view class="order-title">订单信息</view>
					<view :class="['order-status', getStatusClass(currentOrder.status)]">
						{{ getStatusText(currentOrder.status) }}
					</view>
				</view>

				<view class="order-info">
					<view class="info-row">
						<text class="info-label">订单编号</text>
						<text class="info-value">{{ currentOrder.order_id }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">用户信息</text>
						<text class="info-value">{{ currentOrder.user.nickname }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">车桩名</text>
						<text class="info-value">{{ currentOrder.layout.alias }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">所在车桩序号</text>
						<text class="info-value">{{ currentOrder.layout.num }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">借车站点</text>
						<text class="info-value">{{ currentOrder.station.title }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">借车时间</text>
						<text class="info-value">{{ formatDateTime(currentOrder.start_time) }}</text>
					</view>
					<view class="info-row">
						<text class="info-label">使用时长</text>
						<text class="info-value">{{ getUsageDuration(currentOrder) }}</text>
					</view>
				</view>
			</view>

			<!-- 操作按钮区域 -->
			<view class="action-btns" v-if="currentOrder.status === 'paid'">
				<view class="btn btn-cancel" v-if="isEditing" @tap="cancelEditing">取消</view>
				<view class="btn btn-confirm" v-if="isEditing" @tap="confirmSettlement">确认结算</view>
				<view class="btn btn-primary" v-if="!isEditing" @tap="showSettlePopup">立即结算</view>
			</view>

			<!-- 结算历史区域 -->
			<view class="history-card" v-if="currentOrder.status === 'completed' && settlementHistory.length > 0">
				<view class="history-title">结算历史</view>
				<view class="history-list">
					<view class="history-item" v-for="(item, index) in settlementHistory" :key="index">
						<view class="history-header">
							<text class="history-time">{{ formatDateTime(item.time) }}</text>
							<text class="history-operator">操作人: {{ item.operator }}</text>
						</view>
					</view>
				
					<view class="order-info">
						<view class="info-row">
							<text class="info-label">订单编号</text>
							<text class="info-value">{{ v.order_id }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">用户信息</text>
							<text class="info-value">{{ v.user.nickName }}{{v.user.mobile?v.user.mobile:''}}</text>
						</view>
						<view class="info-row">
							<text class="info-label">车桩名</text>
							<text class="info-value">{{ v.layout.alias }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">所在车桩序号</text>
							<text class="info-value">{{ v.layout.num }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">借车站点</text>
							<text class="info-value">{{ v.station.title }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">借车时间</text>
							<text class="info-value">{{ formatDateTime(v.start_time) }}</text>
						</view>
						<view class="info-row">
							<text class="info-label">使用时长</text>
							<text class="info-value">{{ getUsageDuration(v) }}</text>
						</view>
					</view>
				</view>
				
				<!-- 操作按钮区域 -->
				<view class="action-btns" v-if="v.status === 'paid'">
					<view class="btn btn-cancel" v-if="isEditing" @tap="cancelEditing">取消</view>
					<view class="btn btn-confirm" v-if="isEditing" @tap="confirmSettlement">确认结算</view>
					<view class="btn btn-primary" v-if="!isEditing" @tap="showSettlePopup">立即结算</view>
				</view>
				
				<!-- 结算历史区域 -->
				<view class="history-card" v-if="v.status === 'completed' && settlementHistory.length > 0">
					<view class="history-title">结算历史</view>
					<view class="history-list">
						<view class="history-item" v-for="(item, index) in settlementHistory" :key="index">
							<view class="history-header">
								<text class="history-time">{{ formatDateTime(item.time) }}</text>
								<text class="history-operator">操作人: {{ item.operator }}</text>
							</view>
							<view class="history-content">
								<view class="history-row">
									<text class="history-label">结算金额</text>
									<text class="history-value">¥{{ item.amount.toFixed(2) }}</text>
								</view>
								<view class="history-row" v-if="item.remark">
									<text class="history-label">备注</text>
									<text class="history-value">{{ item.remark }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</block>

		<!-- 空状态提示 -->
		<view class="empty-tip" v-if="!currentOrder && !isLoading">
			<image class="empty-image" src="/static/images/empty-order.png"></image>
			<text class="empty-text">请输入已支付的订单号查询</text>
		</view>

		<!-- 加载中状态 -->
		<view class="loading-container" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">查询中...</text>
		</view>

		<!-- 结算确认弹窗 -->
		<uni-popup ref="settlePopup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">确认结算</view>
				<view class="popup-message">是否确认结算此订单？</view>
				<!-- <view class="popup-amount">结算金额：<text class="popup-price">¥{{ totalFee.toFixed(2) }}</text></view> -->
				<view class="popup-amount">订单结束时间：<uni-datetime-picker type="datetime" v-model="end_time" placeholder="默认当前时间" :start="currentOrder.start_time"/></view>
				<view class="popup-buttons">
					<view class="popup-btn popup-btn-cancel" @tap="closeSettlePopup">取消</view>
					<view class="popup-btn popup-btn-confirm" @tap="handleSettlement">确认</view>
				</view>
			</view>
		</uni-popup>

		<!-- 结算成功弹窗 -->
		<uni-popup ref="successPopup" type="dialog">
			<view class="popup-content">
				<view class="popup-title">结算成功</view>
				<view class="success-icon">✓</view>
				<view class="popup-message">订单已成功结算</view>
				<!-- <view class="popup-amount">结算金额：<text class="popup-price">¥{{ totalFee.toFixed(2) }}</text></view> -->
				<view class="popup-buttons">
					<view class="popup-btn popup-btn-confirm" @tap="closeSuccessPopup">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { endOrderApi, getOrderById } from '../../api/order';
	export default {
		data() {
			return {
				// 查询相关
				searchKey: '',
				isLoading: false,

				// 当前订单
				currentOrder: null,
				totalFee: 0,

				// 编辑状态
				isEditing: false,
				settleRemark: '',
				end_time:"",
				// 结算历史
				settlementHistory: []
			};
		},
		methods: {

			// 搜索订单
			async searchOrder() {
				if (!this.searchKey.trim()) {
					uni.showToast({
						title: '请输入搜索内容',
						icon: 'none'
					});
					return;
				}

				this.isLoading = true;
				let res = await getOrderById(this.searchKey);
				console.log(res);
				this.currentOrder = res.data[0]
				console.log(this.currentOrder);
				this.isLoading = false
			},

			// 扫订单码
			scanOrderCode() {
				uni.scanCode({
					success: (res) => {
						this.searchType = 'order';
						this.searchKey = res.result;
						this.searchOrder();
					},
					fail: () => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 扫车辆码
			scanStrollerCode() {
				uni.scanCode({
					success: (res) => {
						this.searchType = 'stroller';
						this.searchKey = res.result;
						this.searchOrder();
					},
					fail: () => {
						uni.showToast({
							title: '扫码失败',
							icon: 'none'
						});
					}
				});
			},

			// 获取订单状态文本
			getStatusText(status) {
				console.log("状态",status)
				const statusMap = {
					'paid': '使用中',
					'completed': '已完成',
					'cancelled': '已取消'
				};
				console.log(status)
				return statusMap[status] || '未知状态';
			},

			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					'using': 'status-using',
					'completed': 'status-completed',
					'cancelled': 'status-cancelled'
				};
				return classMap[status] || '';
			},

			// 计算使用时长
			getUsageDuration(order) {
				if (!order) return '0分钟';

				const startTime = order.start_time;
				const endTime = new Date().getTime();

				const durationMs = endTime - startTime;
				const hours = Math.floor(durationMs / (1000 * 60 * 60));
				const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));

				if (hours > 0) {
					return `${hours}小时${minutes}分钟`;
				} else {
					return `${minutes}分钟`;
				}
			},

			// 计算总费用
			calculateTotal() {
				const baseFee = parseFloat(this.feeDetails.baseFee) || 0;
				const overtimeFee = parseFloat(this.feeDetails.overtimeFee) || 0;
				const damageFee = parseFloat(this.feeDetails.damageFee) || 0;
				const otherFee = parseFloat(this.feeDetails.otherFee) || 0;
				const discount = parseFloat(this.feeDetails.discount) || 0;

				this.totalFee = baseFee + overtimeFee + damageFee + otherFee - discount;

				// 确保不会出现负数
				if (this.totalFee < 0) {
					this.totalFee = 0;
				}
			},

			// 开始编辑
			startEditing() {
				this.isEditing = true;
			},

			// 取消编辑
			cancelEditing() {
				// 重置费用为原值
				if (this.currentOrder) {
					const usageDuration = (new Date().getTime() - this.currentOrder.rentTime) / (60 * 60 * 1000); // 小时为单位
					const baseFee = (10 + usageDuration * 5).toFixed(2);

					this.feeDetails = {
						baseFee,
						overtimeFee: '0.00',
						damageFee: '0.00',
						otherFee: '0.00',
						discount: '0.00'
					};

					this.calculateTotal();
				}

				this.settleRemark = '';
				this.isEditing = false;
			},

			// 确认修改费用
			confirmSettlement() {
				if (this.totalFee <= 0) {
					uni.showToast({
						title: '结算金额必须大于0',
						icon: 'none'
					});
					return;
				}

				this.isEditing = false;
				this.showSettlePopup();
			},

			// 显示结算确认弹窗
			showSettlePopup() {
				this.$refs.settlePopup.open();
			},

			// 关闭结算确认弹窗
			closeSettlePopup() {
				this.$refs.settlePopup.close();
			},

			// 显示结算成功弹窗
			showSuccessPopup() {
				this.$refs.successPopup.open();
			},

			// 关闭结算成功弹窗
			closeSuccessPopup() {
				this.$refs.successPopup.close();

				// 重置数据
				this.currentOrder = null;
				this.feeDetails = {
					baseFee: '0.00',
					overtimeFee: '0.00',
					damageFee: '0.00',
					otherFee: '0.00',
					discount: '0.00'
				};
				this.totalFee = 0;
				this.searchKey = '';
			},

			// 处理结算
			handleSettlement() {
				uni.showLoading({
					title: '结算中...'
				});
				endOrderApi({
					order_id:this.currentOrder.order_id,
					end_time:this.end_time
				}).then((res)=>{
					uni.hideLoading();
					this.closeSettlePopup();
					this.showSuccessPopup();
					this.searchOrder();
				})
			},

			// 格式化日期时间
			formatDateTime(timestamp) {
				if (!timestamp) return '-';

				const date = new Date(timestamp);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hour = String(date.getHours()).padStart(2, '0');
				const minute = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hour}:${minute}`;
			}
		}
	};
</script>

<style>
	/* 美团风格 - 黄色主色调 #FFD100 */
	.container {
		background-color: #F5F5F5;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}

	/* 导航栏 */
	.nav-bar {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 30rpx;
		height: 90rpx;
		background-color: #FFFFFF;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.nav-title {
		font-size: 34rpx;
		font-weight: bold;
		color: #333333;
	}

	/* 卡片通用样式 */
	.search-card,
	.scan-card,
	.order-card,
	.fee-card,
	.history-card {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		margin: 20rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	/* 搜索卡片 */
	.search-title,
	.scan-title,
	.order-title,
	.fee-title,
	.history-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.search-options {
		margin-top: 20rpx;
	}

	.search-option {
		display: flex;
		margin-bottom: 20rpx;
	}

	.option-btn {
		flex: 1;
		text-align: center;
		padding: 15rpx 0;
		font-size: 26rpx;
		color: #666666;
		background-color: #F5F5F5;
		margin-right: 15rpx;
		border-radius: 8rpx;
	}

	.option-btn:last-child {
		margin-right: 0;
	}

	.option-btn.active {
		background-color: #FFD100;
		color: #333333;
	}

	.search-input-box {
		display: flex;
		align-items: center;
	}

	.search-input {
		flex: 1;
		height: 80rpx;
		background-color: #F5F5F5;
		padding: 0 20rpx;
		font-size: 28rpx;
		border-radius: 8rpx;
		margin-right: 15rpx;
	}

	.search-btn {
		width: 150rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background-color: #FFD100;
		color: #333333;
		font-size: 28rpx;
		border-radius: 8rpx;
	}

	/* 扫码卡片 */
	.scan-options {
		display: flex;
		justify-content: space-around;
	}

	.scan-option-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 45%;
		height: 160rpx;
		background-color: #F5F5F5;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #666666;
	}

	.scan-icon {
		font-size: 48rpx;
		margin-bottom: 15rpx;
	}

	/* 订单卡片 */
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #EEEEEE;
		padding-bottom: 15rpx;
		margin-bottom: 15rpx;
	}

	.order-status {
		font-size: 24rpx;
		padding: 6rpx 15rpx;
		border-radius: 30rpx;
	}

	.status-using {
		background-color: #E3F2FD;
		color: #2196F3;
	}

	.status-completed {
		background-color: #E8F5E9;
		color: #4CAF50;
	}

	.status-cancelled {
		background-color: #FFEBEE;
		color: #F44336;
	}

	.order-info {
		margin-top: 20rpx;
	}

	.info-row {
		display: flex;
		margin-bottom: 15rpx;
	}

	.info-label {
		width: 180rpx;
		font-size: 26rpx;
		color: #999999;
	}

	.info-value {
		flex: 1;
		font-size: 26rpx;
		color: #333333;
	}

	/* 费用卡片 */
	.fee-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #EEEEEE;
		padding-bottom: 15rpx;
		margin-bottom: 15rpx;
	}

	.edit-btn {
		font-size: 26rpx;
		color: #2196F3;
	}

	.fee-list {
		margin-top: 20rpx;
	}

	.fee-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.fee-name {
		font-size: 26rpx;
		color: #666666;
	}

	.fee-amount {
		width: 200rpx;
		text-align: right;
		font-size: 26rpx;
		color: #333333;
		background-color: #F5F5F5;
		padding: 10rpx 20rpx;
		border-radius: 8rpx;
	}

	.fee-amount.discount {
		color: #FF5722;
	}

	.total-fee {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #EEEEEE;
	}

	.fee-amount.total {
		font-size: 32rpx;
		font-weight: bold;
		color: #FF5722;
		background-color: transparent;
		padding: 0;
	}

	.remark-section {
		margin-top: 30rpx;
	}

	.remark-label {
		display: block;
		font-size: 26rpx;
		color: #666666;
		margin-bottom: 10rpx;
	}

	.remark-input {
		width: 100%;
		height: 160rpx;
		background-color: #F5F5F5;
		padding: 20rpx;
		font-size: 26rpx;
		border-radius: 8rpx;
		box-sizing: border-box;
	}

	/* 操作按钮 */
	.action-btns {
		display: flex;
		justify-content: space-between;
		margin: 30rpx 20rpx;
	}

	.btn {
		width: 48%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 30rpx;
	}

	.btn-primary {
		background-color: #FFD100;
		color: #333333;
		width: 100%;
	}

	.btn-cancel {
		background-color: #F5F5F5;
		color: #666666;
	}

	.btn-confirm {
		background-color: #FFD100;
		color: #333333;
	}

	/* 结算历史 */
	.history-list {
		margin-top: 20rpx;
	}

	.history-item {
		background-color: #F5F5F5;
		border-radius: 8rpx;
		padding: 20rpx;
		margin-bottom: 15rpx;
	}

	.history-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 15rpx;
		padding-bottom: 15rpx;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.history-time {
		font-size: 24rpx;
		color: #999999;
	}

	.history-operator {
		font-size: 24rpx;
		color: #666666;
	}

	.history-content {
		margin-top: 10rpx;
	}

	.history-row {
		display: flex;
		margin-bottom: 10rpx;
	}

	.history-label {
		width: 140rpx;
		font-size: 26rpx;
		color: #999999;
	}

	.history-value {
		flex: 1;
		font-size: 26rpx;
		color: #333333;
	}

	/* 空状态 */
	.empty-tip {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 30rpx;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
		text-align: center;
	}

	/* 加载中 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 30rpx;
	}

	.loading-spinner {
		width: 80rpx;
		height: 80rpx;
		border: 6rpx solid #F5F5F5;
		border-top: 6rpx solid #FFD100;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #999999;
	}

	/* 弹窗样式 */
	.popup-content {
		background-color: #FFFFFF;
		border-radius: 12rpx;
		padding: 30rpx;
		width: 80vw;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.popup-message {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		margin-bottom: 20rpx;
	}

	.popup-amount {
		font-size: 28rpx;
		color: #666666;
		text-align: center;
		margin-bottom: 30rpx;
	}

	.popup-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #FF5722;
	}

	.popup-buttons {
		display: flex;
		justify-content: space-around;
	}

	.popup-btn {
		width: 48%;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		border-radius: 40rpx;
		font-size: 28rpx;
	}

	.popup-btn-cancel {
		background-color: #F5F5F5;
		color: #666666;
	}

	.popup-btn-confirm {
		background-color: #FFD100;
		color: #333333;
	}

	.success-icon {
		width: 120rpx;
		height: 120rpx;
		line-height: 120rpx;
		text-align: center;
		font-size: 60rpx;
		color: #FFFFFF;
		background-color: #4CAF50;
		border-radius: 50%;
		margin: 0 auto 30rpx;
	}
</style>